const Common = require('../util/common')
const Constant = require('../constant/constant')
const moment = require('moment');
const CollectModel = require('../model/collect');
const ShareModel = require('../model/share');
const UserModel = require('../model/user')
const ForcusFansModel = require('../model/focus_fans');
const sequelize = require('sequelize');
const LikeModel = require('../model/like');
const { Op } = require("sequelize");
const db = require('../db');



let exportObj = {
    collectShare,
    getCollectId,
    getCollectDetail,
    getUserShare,
    cancelCollect,
    setMyAttention,
    cancelCollect,
    cancelAttention,
    getUserAttention,
    getUserFans,
    getUserById,
    update,
    getUserAttentionId
};
// 导出对象，供其它模块调用
module.exports = exportObj;

//用户收藏动态
async function collectShare(req, res) {
    if (Common.check(req.body, ['s_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            return await db.transaction(async (t) => {
                const createRes1 = await CollectModel.create({
                    u_id: req.user.id,
                    s_id: req.body.s_id
                }, { transaction: t })
                const createRes2 = await ShareModel.update({
                    collected: sequelize.literal('`collected` +1')
                }, {
                    where: {
                        id: req.body.s_id,
                    }
                }, { transaction: t })
                if (createRes1 && createRes2) {
                    res.json(resObj)
                } else {
                    res.json(Constant.DEFAULT_ERROR)
                }
            })
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//用户取消收藏
async function cancelCollect(req, res) {
    if (Common.check(req.body, ['s_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            return await db.transaction(async (t) => {
                const cancelRes1 = await CollectModel.destroy({
                    where: {
                        u_id: req.user.id,
                        s_id: req.body.s_id
                    }
                })
                const cancelRes2 = await ShareModel.update({
                    collected: sequelize.literal('`collected` - 1')
                }, {
                    where: {
                        id: req.body.s_id,
                    }
                }, { transaction: t })
                if (cancelRes1 && cancelRes2) {
                    res.json(resObj)
                } else {
                    res.json(Constant.DEFAULT_ERROR)
                }
            })
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//根据ID获取用户信息
async function getUserById(req, res) {
    if (Common.check(req.query, ['u_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            let result = await UserModel.findOne({
                where: {
                    id: req.query.u_id
                }
            })
            if (result) {
                resObj.data = result
                res.json(resObj)
            } else {
                res.json(Constant.DEFAULT_ERROR)
            }
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//获取用户的收藏动态ID
async function getCollectId(req, res) {
    if (Common.check(req.query, ['u_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            let result = await CollectModel.findAll({
                where: {
                    u_id: req.query.u_id
                }
            })
            result.forEach((element, index) => {
                result[index] = element.s_id
            });
            resObj.data = result
            res.json(resObj)
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//获取用户的收藏动态的具体内容
async function getCollectDetail(req, res) {
    if (Common.check(req.query, ['u_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        try {
            ShareModel.belongsTo(UserModel, { foreignKey: 'u_id' })
            let result = await CollectModel.findAll({
                where: {
                    u_id: req.query.u_id
                },
                include: {
                    model: ShareModel,
                    include: { model: UserModel }
                }
            })
            let likeArr = await LikeModel.findAll({
                attributes: ['s_id'],
                where:{
                    u_id : req.user.id,
                    s_id: {
                        [Op.not]: null,
                    }
                }
            })
            likeArr.forEach((item,index)=>{
                likeArr[index] = item.s_id
            })
            result.forEach((element, index) => {
                if(likeArr.includes(element.Share.id)){
                    result[index].Share.dataValues.isLike = 1
                }else{
                    result[index].Share.dataValues.isLike = 0
                }
                result[index] = result[index].Share
            });
            resObj.data = result
            res.json(resObj)
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//获取用户动态
async function getUserShare(req, res) {
    if (Common.check(req.query, ['u_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        ShareModel.belongsTo(UserModel, { foreignKey: 'u_id' })
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        let result = await ShareModel.findAll({
            where: {
                u_id: req.query.u_id
            },
            include: {
                model: UserModel
            }
        })
        let likeArr = await LikeModel.findAll({
            attributes: ['s_id'],
            where:{
                u_id : req.user.id,
                s_id: {
                    [Op.not]: null,
                }
            }
        })
        likeArr.forEach((item,index)=>{
            likeArr[index] = item.s_id
        })
        result.forEach((element, index) => {
            if(likeArr.includes(element.id)){
                result[index].dataValues.isLike = 1
            }else{
                result[index].dataValues.isLike = 0
            }
        });
        resObj.data = result
        res.json(resObj)
        try {
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}

//用户关注
async function setMyAttention(req, res) {
    if (Common.check(req.body, ['to_uid']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        let result = await ForcusFansModel.create({
            from_uid: req.user.id,
            to_uid: req.body.to_uid
        })
        if (result.from_uid && result.to_uid) {
            res.json(resObj)
        } else {
            res.json(Constant.DEFAULT_ERROR)
        }
        try {
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}

//用户取消关注
async function cancelAttention(req, res) {
    if (Common.check(req.body, ['to_uid']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        let result = await ForcusFansModel.destroy({
            where:{
                from_uid: req.user.id,
                to_uid: req.body.to_uid
            }
        })
        if (result) {
            res.json(resObj)
        } else {
            res.json(Constant.DEFAULT_ERROR)
        }
        try {
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}

//获取用户关注
async function getUserAttention(req, res) {
    if (Common.check(req.query, ['from_uid']) === false) {
        res.json(Constant.LACK)
    } else {
        try {
            // 定义一个返回对象
            const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
            ForcusFansModel.belongsTo(UserModel, { foreignKey: 'to_uid' })
            let result = await ForcusFansModel.findAndCountAll({
                where: {
                    from_uid: req.query.from_uid
                },
                include: { model: UserModel }
            })
            result.rows.forEach((element, index) => {
                result.rows[index] = {
                    id: element.User.id,
                    name: element.User.name,
                    avatar: element.User.avatar,
                    controduction: element.User.controduction,
                }
            });
            resObj.data = result.count
            resObj.data = result
            res.json(resObj)
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}

//获取用户粉丝
async function getUserFans(req, res) {
    if (Common.check(req.query, ['to_uid']) === false) {
        res.json(Constant.LACK)
    } else {
        try {
            // 定义一个返回对象
            const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
            ForcusFansModel.belongsTo(UserModel, { foreignKey: 'from_uid' })
            let result = await ForcusFansModel.findAndCountAll({
                where: {
                    to_uid: req.query.to_uid
                },
                include: { model: UserModel }
            })
            result.rows.forEach((element, index) => {
                result.rows[index] = {
                    id: element.User.id,
                    name: element.User.name,
                    avatar: element.User.avatar,
                    controduction: element.User.controduction,
                }
            });
            resObj.data = result.count
            resObj.data = result
            res.json(resObj)
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}

//修改用户信息
async function update(req, res) {
    if (Common.check(req.body, ['u_id']) === false) {
        res.json(Constant.LACK)
    } else {
        // 定义一个返回对象
        const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
        req.body.updated_at = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
        console.log(req.body);
        try {
            const result = await UserModel.update(req.body, {
                where: {
                    id: req.body.u_id
                }
            })
            console.log(result)
            if (result) {
                res.json(resObj)
            } else {
                res.json(Constant.DEFAULT_ERROR)
            }
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }
    }
}

//获取用户关注ID
async function getUserAttentionId(req, res) {
    if (Common.check(req.query, ['from_uid']) === false) {
        res.json(Constant.LACK)
    } else {
        try {
            // 定义一个返回对象
            const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
            // ForcusFansModel.belongsTo(UserModel, { foreignKey: 'to_uid' })
            let result = await ForcusFansModel.findAndCountAll({
                where: {
                    from_uid: req.query.from_uid
                },
                // include: { model: UserModel }
            })
            result.rows.forEach((element, index) => {
                result.rows[index] = element.to_uid
            });
            resObj.data = result
            res.json(resObj)
        } catch (error) {
            console.log(error);
            res.json(Constant.DEFAULT_ERROR)
        }

    }
}
